<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="客户" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          class="!w-240px"
          filterable
          clearable
          lable-key="name"
          placeholder="请选择客户"
          value-key="id"
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id!"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="投资性质" prop="investmentType">
        <el-select
          v-model="queryParams.investmentType"
          placeholder="请选择投资性质"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_INVESTMENT_NATURE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['crm:businessinfo:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['crm:businessinfo:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          v-hasPermi="['crm:businessinfo:submit']"
          type="primary"
          plain
          @click="handleReCreate()"
        >
          <Icon class="mr-5px" icon="ep:refresh" />
          重新发起
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="list"
      :show-overflow-tooltip="true"
      :stripe="true"
    >
      <el-table-column type="selection" />
      <el-table-column align="center" label="客户" prop="customerName" width="300px">
        <template #default="scope">
          <el-link
            :underline="false"
            type="primary"
            @click="openCustomerDetail(scope.row.customerId)"
          >
            {{ scope.row.customerName }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="统一社会信用代码" align="center" prop="socialCrecode" />
      <el-table-column label="注册资本" align="center" prop="registeredCapital" />
      <el-table-column label="投资性质" align="center" prop="investmentType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_INVESTMENT_NATURE" :value="scope.row.investmentType" />
        </template>
      </el-table-column>
      <el-table-column
        label="成立日期"
        align="center"
        prop="registrationTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['crm:businessinfo:update']"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.auditStatus === 0"
            v-hasPermi="['crm:businessinfo:submit']"
            link
            type="primary"
            @click="handleSubmit(scope.row)"
          >
            提交审核
          </el-button>
          <el-button
            v-else
            link
            v-hasPermi="['crm:businessinfo:update']"
            type="primary"
            @click="handleProcessDetail(scope.row)"
          >
            查看审批
          </el-button>
          <el-button
            v-show="
              scope.row.auditStatus === 20 ||
              scope.row.auditStatus === 30 ||
              scope.row.auditStatus === 40 ||
              scope.row.auditStatus === 4
            "
            link
            v-hasPermi="['crm:businessinfo:submit']"
            type="primary"
            @click="handleReCreate(scope.row)"
          >
            重新发起
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['crm:businessinfo:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BusinessinfoForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import * as CustomerApi from '@/api/crm/customer'
import download from '@/utils/download'
import { BusinessinfoApi, BusinessinfoVO } from '@/api/crm/businessinfo'
import BusinessinfoForm from './BusinessinfoForm.vue'

/** CRM 企业工商信息 列表 */
defineOptions({ name: 'Businessinfo' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<BusinessinfoVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerId: null,
  auditStatus: null,
  investmentType: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const customerList = ref<CustomerApi.CustomerVO[]>([]) // 客户列表
const { push } = useRouter()

/** 打开客户详情 */
const openCustomerDetail = (id: number) => {
  push({ name: 'CrmCustomerDetail', params: { id } })
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BusinessinfoApi.getBusinessinfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const tableRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BusinessinfoApi.deleteBusinessinfo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 提交审核 */
const handleSubmit = async (row: BusinessinfoVO) => {
  await message.confirm(`您确定提交审核吗？`)
  await BusinessinfoApi.submit(Array.of(row.id), false)
  message.success('提交审核成功！')
  await getList()
}
/** 重新发起 */
const handleReCreate = async (row?: BusinessinfoVO) => {
  const rows = tableRef.value.getSelectionRows()
  if (rows.length === 0 && row?.processInstanceId == undefined) {
    return message.warning('请选择要再次提交的客户！')
  }
  if (row?.processInstanceId != undefined) {
    await message.confirm(`您确定再次提交【${row?.customerName}】工商信息审核吗？`)
    await BusinessinfoApi.submit(Array.of(row?.id), true)
    message.success('再次提交成功！')
    await getList()
    return
  }
  await message.confirm(
    `您确定再次提交【${rows.map((row: BusinessinfoVO) => row.customerName).join(',')}】工商信息吗？`
  )
  await BusinessinfoApi.submit(Array.of(rows.map((row: BusinessinfoVO) => row.id)), true)
  message.success('再次提交成功！')
  await getList()
}
/** 查看审批详情 */
const handleProcessDetail = async (row: CustomerApi.CustomerVO) => {
  push({ name: 'BpmProcessInstanceDetail', query: { id: row.processInstanceId } })
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BusinessinfoApi.exportBusinessinfo(queryParams)
    download.excel(data, 'CRM 企业工商信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  customerList.value = await CustomerApi.getCustomerSimpleList()
})
</script>
